var express = require('express');
var router = express.Router();
var path=require('path');
var multiparty=require('multiparty');
var fs=require('fs');


/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express',name:'Groots',email:req.session.email});
});

router.get('/login',function(req,res,next){
	res.render('login',{});
});

router.get('/register',function(req,res,next){
	res.render('register',{});
});

router.get('/1*0',function(req,res,next){
	res.send("other_____________>");
});


router.get('/html',function(req,res,next){
	res.sendFile(path.join(__dirname,'../package.json'));
});

router.get('/logout',function(req,res,next){
	req.session.destory(function(err){
		res.redirect('');
	})
})

router.post('/uploadImg',function(req,res,next){
	var form=new multiparty.Form();
	form.encoding="utf-8";
	form.uploadDir='./uploadtemp';
	form.maxFileSize=10*1024*1024;

	form.parse(req,function(err,fields,files){
		var uploadurl='./images/upload/';
		file=files['filedata'];
		originaFilename=file[0].originalFilename;
		tmpPath=file[0].path;
		var timestamp=new Date().getTime();
		uploadurl+=timestamp+originaFilename;
		newPath='./public'+uploadurl;
		var fileReadStream=fs.createReadStream(tmpPath);
		var fileWriteStream=fs.createWriteStream(newPath);
		fileReadStream.pipe(fileWriteStream);
		fileWriteStream.on('close',function(){
			fs.unlinkSync(tmpPath);
			res.send('{"err":"","msg":"'+uploadurl+'""}');
		})
	})
})

module.exports = router;
